package com.blb.aop;

import java.util.Date;

import javax.servlet.http.HttpServletRequest;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.blb.entity.Log;
import com.blb.entity.User;
import com.blb.mapper.LogMapper;
import com.blb.utils.NetworkUtil;
import com.blb.utils.UUIDUtils;

@Aspect
@Component
public class TestAop {
	
	@Autowired
	private HttpServletRequest request;
	
	@Autowired
	private LogMapper logMapper;
	
	@Around("execution(* com.blb.controller111111.*.*(..))")
	public Object printParam(ProceedingJoinPoint pjp) throws Throwable{
		Object[] args = pjp.getArgs();
		
		//用户信息
		Object object2 = request.getSession().getAttribute("user");
		
		//拼接类+方法+参数
		StringBuffer sb = new StringBuffer();
		sb.append(pjp.getSignature().getDeclaringTypeName());
		sb.append(".").append(pjp.getSignature().getName()).append("(");
		for (Object object : args) {
			sb.append(object);
			if (object!=args[args.length-1]) sb.append(", ");
		}
		sb.append(")");
		
		Log log = new Log();
		log.setId(UUIDUtils.getID());
		log.setCreateTime(new Date());
		log.setIp(NetworkUtil.getIpAddress(request));
		log.setMethod(sb.toString());
		log.setUrl(request.getRequestURL().toString());
		if (object2==null) {
			log.setUserId("");
			log.setUsername("");
		}else {
			User user = (User) object2;
			log.setUserId(user.getId());
			log.setUsername(user.getUsername());
		}
		
		logMapper.insert(log);
		
		Object object = pjp.proceed();
		return object;
	}
}
